package com.cn.order.service;



import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.cn.api.OrderCoreService;
import com.cn.dot.AliPayDTO;
import com.cn.dto.FindDto;
import com.cn.dto.OrderDTO;
import com.cn.order.config.AlipayConfig;

import com.cn.order.entity.OVid;
import com.cn.order.entity.Order;
import com.cn.order.mapper.OrderMapper;
import com.cn.order.util.Exchange;
import com.cn.order.util.QRCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Component
@RestController
@RequestMapping("/api/order")
@Slf4j
public class OrderServiceImpl implements OrderCoreService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private Exchange exchange;


    @Override
    @GetMapping("/findAll")//查找所有
    public List<OrderDTO> findAll(FindDto findDto) {
        List<OrderDTO> orderDTOS=exchange.changeOrders(orderMapper.findAll(findDto));
        return orderDTOS;
    }


    @Override
    @GetMapping("/findByOrderNumber")//订单号查找订单
    public OrderDTO findByOrderNumber(String orderNumber) {
        Order order=orderMapper.findByOrderNumber(orderNumber);
        OrderDTO orderDTO=new OrderDTO();
        orderDTO.setOrderNumber(order.getOrderNumber());
        orderDTO.setUserId(order.getUserId());
        orderDTO.setOrderStatus(order.getOrderStatus());
        orderDTO.setAmount(order.getAmount());
        orderDTO.setProductId(order.getProductId());
        orderDTO.setCouponId(order.getCouponId());
        orderDTO.setVisitorNumber(order.getVisitorNumber());
        orderDTO.setTravelDate(order.getTravelDate());
        orderDTO.setOrderDate(order.getOrderDate());
        return orderDTO;
    }


    @Override
    @PostMapping("/generateOrder")//生成订单
    public int generateOrder(OrderDTO orderDTO) {
        return orderMapper.generateOrder(orderDTO);
    }


    @Override
    @PostMapping("/delete")//删除订单
    public int delete(String orderNumber) {
        return orderMapper.delete(orderNumber);
    }


    @Override
    @PostMapping("/updateStatus")//修改订单状态
    public int updateStatus(String orderNumber) {
        return orderMapper.updateStatus(orderNumber);
    }

    @Override
    @PostMapping("/updateStatusCancel")//取消订单
    public int updateStatusCancel(String orderNumber) {
        return orderMapper.updateStatusCancel(orderNumber);
    }

    @Override
    @PostMapping("/addRelation")//添加订单与出行人关系
    public int addRelation(String orderNumber,List<Integer> visitorId) {
        OVid oVid = new OVid();
        oVid.setOrderNumber(orderNumber);
        oVid.setVisitorIdList(visitorId);
        return orderMapper.addRelation(oVid);
//        return orderMapper.addRelation(orderNumber,visitorId);
    }

    @Override
    @PostMapping("competitionForOrders")
    public OrderDTO competitionForOrders(int adminId, String orderNumber) {
        int byAdminId = orderMapper.findByAdminId(orderNumber);
        synchronized (String.valueOf(adminId)){
            if (String.valueOf(byAdminId)==null){
                int i = orderMapper.updateAdminID(orderNumber);
                Order byOrderNumber = orderMapper.findByOrderNumber(orderNumber);
                OrderDTO orderDTO=exchange.changeOrder(byOrderNumber);
                orderDTO.setAdminId(i);
                return orderDTO;
            }
            return null;
        }
    }
    @PostMapping("findByAdminId")
    public int success(int adminId){
        int byAdminId = orderMapper.findAdminIdByUser(adminId);
        return byAdminId;
    }
    @PostMapping("fail")
    public int fail(String orderNumber){
        int i = orderMapper.updateReason(orderNumber);
        return i;
    }

    @PostMapping("/generateCode")
    public String generateCode(AliPayDTO aliPayDTO){
        QRCodeUtil qrCodeUtil = new QRCodeUtil();
        String qrCode = null;
        String traceNo=aliPayDTO.getTraceNo();
        String totalAmount = aliPayDTO.getTotalAmount();
        String website="http://ibkjgk.natappfree.cc/order/alipaytest?traceNo="+traceNo+"&totalAmount="+totalAmount;
        try {
            qrCode = qrCodeUtil.createQRCode(website, 200, 200);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return qrCode;
    }

    @Override
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception {
        log.info("支付成功, 进入同步通知接口...");
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        log.info("支付宝返回参数："+params);
        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        if(signVerified) {
            //商户订单号
            String orderNo = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            //alipayService.onlyBuy(orderNo);

            log.info("******************** 支付成功(支付宝同步通知) ********************");
            log.info("* 订单号: {}", orderNo);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
            log.info("***************************************************************");
            orderMapper.updateStatus("orderNo");
        }else{
            log.error("同步回调签名验证失败");
        }
        return "支付成功！";
    }
//
    @Override
    @PostMapping(value = "/payReFund")
    public String payReFund(String trade_no, String refund_amount) {
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);
        AlipayTradeRefundRequest req = new AlipayTradeRefundRequest();

        String out_request_no = System.currentTimeMillis()+"";

        req.setBizContent("{\"out_trade_no\":" + trade_no + "," + "\"refund_amount\":" + refund_amount + ","
                + "\"out_request_no\":\"" + out_request_no + "\"}");
        AlipayTradeRefundResponse resp = null;
        try {
            resp = alipayClient.execute(req);
        } catch (AlipayApiException e) {
            return "退款失败";
        }
        if (resp.isSuccess()) {
            return "退款成功";
        } else {
            return "退款失败";
        }

    }
}
